<template>
  <div>
    <el-row>
      <el-col :span="24" align="right">
        <el-button type="primary" @click="addPeople()">添加</el-button>
      </el-col>
    </el-row>
    <Table :tableArr="membersList" :pagination="data.page" :columns="data.columns" :isCheckbox="true"
      :total="membersList.length" :dataSources="true">
      <template #operate="{ row }">
        <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
      </template>
    </Table>

    <el-dialog v-model="data.addPeople" append-to-body width="50%" top="10vh" :show-close="false"
      :close-on-click-modal="false">
      <template #title>
        <div class="my-header">
          <el-tabs v-model="data.activeName" class="demo-tabs">
            <el-tab-pane label="添加人员" name="first">
              <el-form :model="form" ref="ruleFormRef" :rules="rules" status-icon label-position="left" label-width="90px"
                :inline="true" class="demo-form-inline">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="单位" prop="unit">

                      <!-- <el-tree-select v-model="value" :data="data.unitSelet" :props="{ value: 'id', label: 'name'}"
                        @change="advancedSelect" :render-after-expand="false" /> -->
                      <!-- <SelectOption :options="data.unitSelet" @change-value="changeValue">
                      </SelectOption> -->
                      <el-cascader ref="cascaderRef" v-model="selectedIds" :options="selOp"
                        :props="{ emitPath: false, value: 'id', label: 'name' }" @change="handleChange"
                        :show-all-levels="false" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="人员" prop="memberName">
                      <SelectOption :selectValue="form.memberName" :options="store.state.projectCenter.allUserList"
                        @change-value="changeValue1">
                      </SelectOption>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="平台角色" prop="roleName">
                      <SelectOption :selectValue="form.roleName" :options="data.roleList" @change-value="changeValue2">
                      </SelectOption>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.addPeople = false">关闭</el-button>
          <el-button type="primary" @click="save()">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  
<script lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import { useStore } from 'vuex'
import common from '../../common/common.json'
import SelectOption from '../selectOption/index.vue'
import Table from '../table/table.vue'
import { tips } from '../tips/tips'
// import { getPersonnelData } from '../../../api/commom'
import { delectPeople } from '../../../api/hignEnd'

export default {
  components: {
    Table,
    SelectOption
  },
  emits: {
    dataChange: null,
    paramsChange: null,
  },
  props: {
    members: {
      type: Array,
      required: true,
    }
  },
  setup(props, { emit }) {
    const store = useStore()
    const selectedIds = ref()
    let value = ref([])
    let data = reactive({
      selectedIds: '',
      activeName: ref('first'),
      columns: common.platformUserHeader,
      page: {
        page: 1,
        limit: 10,
        total: 0,
      },
      addPeople: false,
      unitSelet: computed(() => store.state.technologyStrength.unitSelet),
      // usersSelet: computed(() => store.state.technologyStrength.usersSelet),
      usersSelet: [],
      roleList: computed(() => store.state.technologyStrength.ptRoleList),
    })
    const selOp = computed(() => {
      const obj = store.state.technologyStrength.orgAllList
      let arr = [] as any
      for (let key in obj) {
        arr.push(obj[key])
      }
      return arr
    })

    const membersList = ref(props.members)

    watch(props, (newValue, oldValue) => {
      membersList.value = newValue.members
    });


    const form = reactive({
      unit: '',
      unitId: '',
      roleCode: "",
      roleName: "",
      memberType: '',
      memberName: "",
      memberId: "",
      sort: 0,
      // id: computed(() => store.state.technologyStrength.rowId),
    })

    // const changeValue = async (item) => {
    //   form.unitId = item.id
    //   form.unit = item.name
    //   const params = {
    //     currentPage: 1,
    //     isPage: 0,
    //     orgIds: [item.id],
    //     size: 10000,
    //     type: 0
    //   }
    //   const rst = await getPersonnelData(params)
    //   data.usersSelet = rst.data.data
    // }
    const changeValue = async (item) => {
      form.unitId = item.id
      form.unit = item.name
      const params = {
        currentPage: 1,
        isPage: 0,
        orgIds: [item.id],
        size: 10000,
        type: 0
      }
      // const rst = await getPersonnelData(params)
      // data.usersSelet = rst.data.data
    }

    const changeValue1 = (item) => {
      form.memberId = item.userId
      form.memberName = item.username
    }
    const changeValue2 = (item) => {
      form.roleCode = item.id
      form.roleName = item.itemText
    }

    const rules = reactive({
      unit: [
        { required: true, message: '请选择单位', trigger: 'change' },
      ],
      memberName: [
        { required: true, message: '请选择人员', trigger: 'change', },
      ],
      roleName: [
        { required: true, message: '请选择平台角色', trigger: 'change', },
      ]
    })

    const addPeople = () => {
      data.addPeople = true
    }

    const findItemNested = (arr, itemId, nestingKey) => (
      arr.reduce((a, item) => {
        if (a) return a;
        if (item.id === itemId) return item;
        if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)
      }, null)
    );

    const handleChange = (value) => {
      const item = findItemNested(selOp.value, value, 'children')
      // changeValue(item)
    }

    const ruleFormRef = ref()
    const save = async () => {
      await ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
          let obj = {
            unit: form.unit,
            unitId: form.unitId,
            roleCode: form.roleCode,
            roleName: form.roleName,
            memberType: form.memberType,
            memberName: form.memberName,
            memberId: form.memberId,
            sort: form.sort,
          }
          if (JSON.stringify(membersList.value).indexOf(JSON.stringify(obj)) == -1) {
            membersList.value.push(obj)
          } else {
            tips('不可添加相同成员', 'warning')
          }

          Object.keys(form).forEach((key) => {
            form[key] = ''
          })
          selectedIds.value = ''
          emit('paramsChange', membersList)
          data.addPeople = false
        } else {
          console.log('校验失败')
        }
      })
    }

    const handleDelete = async (row) => {
      if (row.id) {
        let res = await delectPeople(row.id)
        if (res.data.success) {
          emit('dataChange')
        }
      } else {
        var index = membersList.value.indexOf(row);
        if (index > -1) {//大于0 代表存在，
          membersList.value.splice(index, 1);//存在就删除
        }
      }
    }

    const advancedSelect = (value) => {
      console.log(value)
    }


    return {
      data,
      form,
      store,
      membersList,
      value,
      rules,
      ruleFormRef,
      handleChange,
      selOp,
      advancedSelect,
      selectedIds,

      addPeople,
      close,
      handleDelete,
      save,
      // changeValue,
      changeValue1,
      changeValue2
    }
  },
}
</script>
  
<style scoped lang="scss">
.demo-form-inline .el-form-item {
  width: 70%;
}

.el-select {
  width: 100%;
  margin: 0;
}
</style>
  